<?php
class Content extends AppModel {
    
    public $validate = array();
    public function deleteContent($id){
        $data = $this->find('first',array('conditions'=>array('Content.id'=>$id)));
        if(isset($data['Content']['type'])){
            switch($data['Content']['type']){
                case 'video' :
                    
                    //Get all data
                    $video = reset($this->query(sprintf('select * from videos as `Video` where content_id = %d',$id)));
                    
                    //Delete absolute file
                    if(isset($video['Video']['file_id']) && isset($video['Video']['thumb_id'])){
                        $files = $this->query(sprintf('select * from files as `File` where id in (%s)', implode(',',array($video['Video']['file_id'],$video['Video']['thumb_id']))));
                        foreach($files as $key=>$val){
                            
                            if(file_exists($val['File']['absolute_path'])){
                                $tmp = new File($val['File']['absolute_path'],false, 0777);
                                if($tmp->delete()) {
                                    CakeLog::info('File delete :'.$val['File']['absolute_path']);
                                }else{  
                                    CakeLog::info('File delete error :'.$val['File']['absolute_path']);
                                }
                            }else{
                                CakeLog::info('File not found :'.$val['File']['absolute_path']);
                            }
                            
                            //Delete file entry in files table
                            if(isset($val['File']['id'])){
                                $tmp = $this->query(sprintf('delete from files where id = %d',$val['File']['id']));
                                if(empty($tmp)){
                                    CakeLog::info('File entry delete :'.$val['File']['id']);
                                }
                            }
                        }
                    }
                    
                    //Video entry delete in video table
                    $tmp = $this->query(sprintf('delete from videos where content_id = %d',$video['Video']['content_id']));
                    if(empty($tmp)){
                        CakeLog::info('Video entry delete content_id :'.$video['Video']['content_id']);
                    }
                    
                    //Delete entry from content table
                    $tmp = $this->query(sprintf('delete from contents where id = %d',$id));
                    if(empty($tmp)){
                        CakeLog::info('Content entry delete id :'.$id);
                    }
                    
                    return true;
                    break;
                default :
                    echo 'id not found';
                    break;
            }
        }
    }
}